package org.darcy.youchat.activity.login;

import android.content.Intent;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.MenuItem;
import android.widget.TextView;

import org.darcy.youchat.R;
import org.darcy.youchat.activity.BaseActivity;
import org.darcy.youchat.activity.MainActivity;
import org.darcy.youchat.databinding.ActivityLoginBinding;
import org.darcy.youchat.model.UserCache;
import org.darcy.youchat.nimsdk.NimAccountSDK;
import org.darcy.youchat.nimsdk.NimUserInfoSDK;
import org.darcy.youchat.utils.UIUtils;
import com.netease.nimlib.sdk.AbortableFuture;
import com.netease.nimlib.sdk.RequestCallback;
import com.netease.nimlib.sdk.auth.LoginInfo;

import java.util.ArrayList;
import java.util.List;

import me.drakeet.materialdialog.MaterialDialog;

/**
 * 登录界面
 */
public class LoginActivity extends BaseActivity {
    /**
     * 视图绑定类
     */
    private ActivityLoginBinding binding;

    @Override
    public void initView() {
        binding = ActivityLoginBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());
        setSupportActionBar(binding.mToolbar.toolbar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setTitle("使用手机号登录");
        binding.mToolbar.toolbar.setNavigationIcon(R.mipmap.ic_back);
        if (!TextUtils.isEmpty(binding.etPhone.getText().toString()) && !TextUtils.isEmpty(binding.etPwd.getText().toString())) {
            binding.btnLogin.setEnabled(true);
        }
    }

    @Override
    public void initListener() {
        /*------------------ 监听编辑框，变换样式 begin ------------------*/
        binding.etPhone.setOnFocusChangeListener((v, hasFocus) -> {
            if (hasFocus) {
                binding.vLinePhone.setBackgroundColor(UIUtils.getColor(R.color.green0));
            } else {
                binding.vLinePhone.setBackgroundColor(UIUtils.getColor(R.color.line));
            }
        });
        binding.etPwd.setOnFocusChangeListener((v, hasFocus) -> {
            if (hasFocus) {
                binding.vLinePwd.setBackgroundColor(UIUtils.getColor(R.color.green0));
            } else {
                binding.vLinePwd.setBackgroundColor(UIUtils.getColor(R.color.line));
            }
        });
        binding.etPhone.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (!TextUtils.isEmpty(binding.etPhone.getText().toString()) && !TextUtils.isEmpty(binding.etPwd.getText().toString())) {
                    binding.btnLogin.setEnabled(true);
                } else {
                    binding.btnLogin.setEnabled(false);
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
        binding.etPwd.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                binding.btnLogin.setEnabled(!TextUtils.isEmpty(binding.etPhone.getText().toString()) && !TextUtils.isEmpty(binding.etPwd.getText().toString()));
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
        /*------------------ 监听编辑框，变换样式 end ------------------*/

        binding.btnLogin.setOnClickListener(v -> {
            doLogin();
            binding.btnLogin.setEnabled(false);
        });
        binding.tvProblem.setOnClickListener(v -> {
            UIUtils.showToast("有问题找老师，我也没着");
        });
        binding.tvOtherLogin.setOnClickListener(v -> {
            startActivity(new Intent(this, OtherLoginActivity.class));
        });
    }


    /**
     * 登录
     */
    public void doLogin() {
        showWaitingDialog("正在登录...");
        String mUsername = binding.etPhone.getText().toString().trim();
        String mPassword = binding.etPwd.getText().toString().trim();
        //判断非空
        if (TextUtils.isEmpty(mUsername) || TextUtils.isEmpty(mPassword)) {
            UIUtils.showToast("用户名和密码不能为空");
            return;
        }
        // mToken = MD5Utils.decode16(mPassword);
        String mToken = mPassword;
        //配置登录信息，并开始登录
        AbortableFuture<LoginInfo> mLoginRequest
                = NimAccountSDK.login(mUsername, mToken, new RequestCallback<LoginInfo>() {
            @Override
            public void onSuccess(LoginInfo param) {
                onLoginDone();
                //保存用户名到内存中
                UserCache.setAccount(mUsername);
                //保存用户信息到本地，方便下次启动APP做自动登录用
                NimAccountSDK.saveUserAccount(mUsername);
                NimAccountSDK.saveUserToken(mToken);
                //更新本地用户资料
                List<String> list = new ArrayList<>();
                list.add(UserCache.getAccount());
                NimUserInfoSDK.getUserInfosFormServer(list, null);
                //进行主界面
                Intent intent = new Intent(LoginActivity.this, MainActivity.class);
                intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
                startActivity(intent);
                finish();
            }

            @Override
            public void onFailed(int code) {
                onLoginDone();
                if (code == 302 || code == 404) {
                    MaterialDialog materialDialog = showMaterialDialog("", "", "确定", "", v -> hideMaterialDialog(), null);
                    TextView tv = new TextView(LoginActivity.this);
                    tv.setText("账号或密码错误，请重新填写。");
                    tv.setTextColor(UIUtils.getColor(R.color.black0));
                    tv.setPadding(0, UIUtils.dip2Px(15), 0, UIUtils.dip2Px(18));
                    materialDialog.setContentView(tv);
                } else {
                    UIUtils.showToast("登录失败: " + code);
                }
            }

            @Override
            public void onException(Throwable exception) {
                onLoginDone();
                UIUtils.showToast("无效输入");
            }
        });
    }

    private void onLoginDone() {
        hideWaitingDialog();
        binding.btnLogin.setEnabled(true);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            //ToolBar的返回点击事件
            case android.R.id.home:
                finish();
                break;
        }
        return super.onOptionsItemSelected(item);
    }


}